package com.sina.mysql.utils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @ClassName SystemClock
 * @Description:
 * @Author 段浩杰
 * @Date 2018/8/22 17:38
 * @Version 1.0
 */
public class SystemClock {


    private static final SystemClock INSTANCE = new SystemClock(1);

    private final long period;
    private final AtomicLong now;

    private SystemClock(long period) {
        this.period = period;
        this.now = new AtomicLong(System.currentTimeMillis());
        scheduleClockUpdating();
    }


    private void scheduleClockUpdating() {
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(runnable -> {
            Thread thread = new Thread(runnable, "System Clock");
            thread.setDaemon(true);
            return thread;
        } );
        scheduler.scheduleAtFixedRate( () -> now.set(System.currentTimeMillis()), period, period, TimeUnit.MILLISECONDS);
    }

    public static long now() {
        return INSTANCE.now.get();
    }


}